﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Camelio.BLL;
using System.Collections;

namespace Camelio
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }
        private void MainForm_Load(object sender, EventArgs e)
        {
            // Casher Tab
            Program.grdCasherDT.Columns.Add("رقم المنتج", typeof(int));
            Program.grdCasherDT.Columns.Add("اسم المنتج", typeof(string));
            Program.grdCasherDT.Columns.Add("العدد", typeof(int));
            Program.grdCasherDT.Columns.Add("اجمالى السعر", typeof(float));
            button9_Click(sender, e);
            // Search Tab
            button7_Click(sender, e);
            // Creation Tab
            button4_Click(sender, e);
            // Daily Sales Tab
            button5_Click(sender, e);
            // Sales Tab
            button8_Click(sender, e);
            // Suppliers Tab
            btnRefreshSupplier_Click(sender, e);
            // GENERAL
            if (Camelio.Properties.Settings.Default.LoginType != "admin")
            {
                tabControl1.TabPages.RemoveByKey("tabProducts");
                tabControl1.TabPages.RemoveByKey("tabDailySales");
                tabControl1.TabPages.RemoveByKey("tabSales");
                tabControl1.TabPages.RemoveByKey("tabSuppliers");
                button2.Visible = false;
            }
            else
            {
                Program.userName = "admin";
            }
        }

        private void checkQuan()
        {
            int availPieces = int.Parse(txtAvalbilePieces.Text);
            int quan = int.Parse(txtNumOfProd.Text);

            if (availPieces < quan)
            {
                label6.ForeColor = Color.Red;
                label4.ForeColor = Color.Red;
                btnAdd.Enabled = false;
            }
            else
            {
                label6.ForeColor = Color.Black;
                label4.ForeColor = Color.Black;
                btnAdd.Enabled = true;
            }
        }

        private void ComboProdName_SelectedValueChanged2(object sender, EventArgs e)
        {
            string ID = ComboProdName.SelectedValue.ToString();
            Products Prodd = new Products();
            Prodd.LoadByPrimaryKey(int.Parse(ComboProdName.SelectedValue.ToString()));
            if (Prodd.RowCount > 0)
            {
                txtPrice.Text = Prodd.ProdPrice.ToString();
                txtAvalbilePieces.Text = Prodd.ProdQuantity.ToString();
                txtProdNum.Text = Prodd.ProdID.ToString();
                txtNumOfProd.Text = "1";
            }
            else
            {
                textBox1.Text = (int.Parse(txtNumOfProd.Text) * float.Parse(txtPrice.Text)).ToString();
            }

            checkQuan();
        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            //if (txtNumOfProd.Text == "1")
            //{
            //    textBox1.Text = txtPrice.Text;
            //}
            // else
            if (txtNumOfProd.Text != null)
            {
                textBox1.Text = ((float.Parse(txtNumOfProd.Text) * float.Parse(txtPrice.Text)).ToString());
            }
        }
        private void txtProdNum_TextChanged(object sender, EventArgs e)
        {
            if (txtProdNum.Text.Length >= 2)
            {
                Products Prodd = new Products();
                Prodd.LoadByPrimaryKey(int.Parse(txtProdNum.Text));
                if (Prodd.RowCount > 0)
                {
                    try
                    {
                        ComboProdName.SelectedValue = txtProdNum.Text;
                    }
                    catch (Exception)
                    {
                        
                    }
                }
                if (txtNumOfProd.Text == "1")
                {
                    textBox1.Text = txtPrice.Text;
                }
            }
        }
        private void ColorSearch()
        {
            Products prod = new Products();
            prod.GetDestinctColors();

            DataTable dt = prod.DefaultView.ToTable();
            List<string> str = new List<string>();
            str.AddRange(dt.Rows.OfType<DataRow>().Select(dr => dr.Field<string>("ProdColor")).ToList());

            str.Insert(0, "الكل");
            comboColor.DataSource = str;
        }
        private void TypeSearch()
        {
            Products prod = new Products();
            prod.GetPType();
            DataTable dt = prod.DefaultView.ToTable();
            List<string> str = new List<string>();
            str.AddRange(dt.Rows.OfType<DataRow>().Select(dr => dr.Field<string>("ProdType")).ToList());

            str.Insert(0, "الكل");
            comboTybe.DataSource = str;
        }
        private void CatSearch()
        {
            Categories cat = new Categories();
            cat.LoadAll();
            DataTable dt = cat.DefaultView.ToTable();
            List<string> str = new List<string>();
            str.AddRange(dt.Rows.OfType<DataRow>().Select(dr => dr.Field<string>("CatName")).ToList());
            str.Insert(0, "الكل");
            comboCat.DataSource = str;
        }
        private void SizeSearch()
        {
            Products Prod = new Products();
            Prod.GetSize();
            DataTable dt = Prod.DefaultView.ToTable();
            List<string> str = new List<string>();
            str.AddRange(dt.Rows.OfType<DataRow>().Select(dr => dr.Field<string>("ProdSize")).ToList());

            str.Insert(0, "الكل");
            comboSize.DataSource = str;
        }

        private void label5_Click(object sender, EventArgs e)
        {

        }

        private void btnNumPlus_Click(object sender, EventArgs e)
        {
            int QuantNum = int.Parse(txtNumOfProd.Text);
            QuantNum++;
            txtNumOfProd.Text = QuantNum.ToString();
        }

        private void btnNumMinus_Click(object sender, EventArgs e)
        {
            if (int.Parse(txtNumOfProd.Text) > 1)
            {
                int QuantNum = int.Parse(txtNumOfProd.Text);
                QuantNum--;
                txtNumOfProd.Text = QuantNum.ToString();
            }
        }

        private void txtNumOfProd_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            SettingsForm sf = new SettingsForm();
            sf.ShowDialog();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (Program.grdCasherDT.Rows.Count == 0)
            {
                MessageBox.Show("لم يتم اضافة منتج", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }
            else
            {
                int quan = 0;
                float Price = 0;
                int InvoiceID = 0;

                for (int i = 0; i < Program.grdCasherDT.Rows.Count; i++)
                {
                    InvoiceID = int.Parse(Program.grdCasherDT.Rows[i]["رقم المنتج"].ToString());
                    Price = float.Parse(Program.grdCasherDT.Rows[i]["اجمالى السعر"].ToString());
                    quan = int.Parse(Program.grdCasherDT.Rows[i]["العدد"].ToString());

                    Sales dal = new Sales();
                    dal.AddNew();
                    dal.ProdID = InvoiceID;
                    dal.SaledPrice = Price;
                    dal.SaleQuantity = quan;
                    dal.SaleDate = DateTime.Now.Date.ToShortDateString();
                    dal.SaleTime = DateTime.Now.ToShortTimeString();
                    dal.Save();

                    Products Prro = new Products();
                    Prro.LoadByPrimaryKey(InvoiceID);
                    Prro.ProdQuantity = (Prro.ProdQuantity - quan);
                    Prro.Save();
                }
                MessageBox.Show("تمت العملية بنجاح", "Done", MessageBoxButtons.OK, MessageBoxIcon.Information);
                Program.grdCasherDT.Rows.Clear();
                lblTotalInvoice.Text = "0";
            }
        }

        private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void label12_Click(object sender, EventArgs e)
        {

        }

        private void textBox6_TextChanged(object sender, EventArgs e)
        {

        }

        private void button3_Click(object sender, EventArgs e)
        {

        }

        private void btnCreateProduct_Click(object sender, EventArgs e)
        {
            if (checkCreateEmptyFields())
            {
                MessageBox.Show("تأكد من الخانات الفارغة", "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                Products newProd = new Products();
                if (Program.createFunction == "create")
                {
                    newProd.AddNew();

                    Products checkProd = new Products();
                    checkProd.LoadByPrimaryKey(int.Parse(txtCreateProdNum.Text));
                    if (checkProd.RowCount > 0)
                    {
                        MessageBox.Show("رقم المنتج متقرر", "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        goto Exit;
                    }
                    newProd.ProdID = int.Parse(txtCreateProdNum.Text);
                }
                else if (Program.createFunction == "edit")
                {
                    newProd.LoadByPrimaryKey(int.Parse(txtCreateProdNum.Text));
                }
                newProd.CatID = int.Parse(cbCreateProdCat.SelectedValue.ToString());
                newProd.ProdName = txtCreateProdName.Text;
                newProd.ProdType = txtCreateProdType.Text;
                newProd.ProdQuantity = int.Parse(txtCreateProdQuantity.Text);
                newProd.ProdSize = txtCreateProdSize.Text;
                newProd.ProdNetPrice = float.Parse(txtCreateProdNetPrice.Text);
                newProd.ProdPrice = float.Parse(txtCreateProdPrice.Text);
                newProd.ProdIsSoiree = ckbCreateSoiree.Checked;
                newProd.ProdColor = txtCreateProdColor.Text;
                newProd.Save();
                button4_Click(sender, e);
                MessageBox.Show("تمت العملية بنجاح", "Done", MessageBoxButtons.OK, MessageBoxIcon.Information);

            Exit:
                Program.createFunction = "create";
            }
        }

        bool checkCreateEmptyFields()
        {
            bool isEmpty = false;

            if (string.IsNullOrWhiteSpace(txtCreateProdNum.Text) || txtCreateProdNum.Text.Length < 3)
            {
                isEmpty = true;
            }
            if (string.IsNullOrWhiteSpace(txtCreateProdName.Text))
            {
                isEmpty = true;
            }
            if (string.IsNullOrWhiteSpace(txtCreateProdNetPrice.Text))
            {
                isEmpty = true;
            }
            if (string.IsNullOrWhiteSpace(txtCreateProdPrice.Text))
            {
                isEmpty = true;
            }
            if (string.IsNullOrWhiteSpace(txtCreateProdQuantity.Text))
            {
                isEmpty = true;
            }
            if (string.IsNullOrWhiteSpace(txtCreateProdSize.Text))
            {
                isEmpty = true;
            }
            if (string.IsNullOrWhiteSpace(txtCreateProdType.Text))
            {
                isEmpty = true;
            }
            if (string.IsNullOrWhiteSpace(txtCreateProdColor.Text))
            {
                isEmpty = true;
            }
            return isEmpty;
        }

        private void button4_Click(object sender, EventArgs e)
        {
            Products prod2 = new Products();
            prod2.getAllProd();
            grdViewProductsAll.DataSource = prod2.DefaultView;

            Categories Cats = new Categories();
            Cats.LoadAll();
            cbCreateProdCat.DataSource = Cats.DefaultView;
            cbCreateProdCat.DisplayMember = "CatName";
            cbCreateProdCat.ValueMember = "CatID";

            Products prod3 = new Products();
            prod3.getAllProd();
            grdViewProductsAll.DataSource = prod3.DefaultView;
        }

        private void btnCreateClearFields_Click(object sender, EventArgs e)
        {
            txtCreateProdName.Text = "";
            txtCreateProdNetPrice.Text = "";
            txtCreateProdNum.Text = "";
            txtCreateProdPrice.Text = "";
            txtCreateProdQuantity.Text = "";
            txtCreateProdSize.Text = "";
            txtCreateProdType.Text = "";
            ckbCreateSoiree.Checked = false;
            cbCreateProdCat.SelectedIndex = 0;
            txtCreateProdColor.Text = "";

            Program.createFunction = "create";
            txtCreateProdNum.ReadOnly = false;
            btnCreateProduct.Text = "انشاء";
            btnCreateProduct.BackColor = Color.LightGreen;
        }

        private void grdViewProductsAll_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            var senderGrid = (DataGridView)sender;

            if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn && e.RowIndex >= 0)
            {
                if (senderGrid.Columns[e.ColumnIndex].HeaderText == "تعديل")
                {
                    Program.createFunction = "edit";
                    txtCreateProdName.Text = grdViewProductsAll["ColProdName", e.RowIndex].Value.ToString();
                    txtCreateProdNum.Text = grdViewProductsAll["ColProdNum", e.RowIndex].Value.ToString();
                    txtCreateProdSize.Text = grdViewProductsAll["ColProdSize", e.RowIndex].Value.ToString();
                    txtCreateProdType.Text = grdViewProductsAll["ColProdType", e.RowIndex].Value.ToString();
                    txtCreateProdQuantity.Text = grdViewProductsAll["ColProdQuantity", e.RowIndex].Value.ToString();
                    txtCreateProdPrice.Text = grdViewProductsAll["ColProdPrice", e.RowIndex].Value.ToString();
                    txtCreateProdNetPrice.Text = grdViewProductsAll["ColProdNetPrice", e.RowIndex].Value.ToString();
                    ckbCreateSoiree.Checked = (bool)grdViewProductsAll["ColIsSoiree", e.RowIndex].Value;
                    cbCreateProdCat.Text = grdViewProductsAll["ColProdCat", e.RowIndex].Value.ToString();
                    txtCreateProdColor.Text = grdViewProductsAll["ColProdColor", e.RowIndex].Value.ToString();

                    btnCreateProduct.Text = "تعديل";
                    btnCreateProduct.BackColor = Color.Orange;
                    txtCreateProdNum.ReadOnly = true;
                }
                else if (senderGrid.Columns[e.ColumnIndex].HeaderText == "مسح")
                {

                    DialogResult res = MessageBox.Show("هل تريد مسح هذا المنتج نهايئا ؟", "تأكيد المسح", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (res == DialogResult.Yes)
                    {
                        string prodID = grdViewProductsAll["ColProdNum", e.RowIndex].Value.ToString();
                        Products deleteProd = new Products();
                        deleteProd.LoadByPrimaryKey(int.Parse(prodID));
                        deleteProd.MarkAsDeleted();
                        deleteProd.Save();

                        button4_Click(sender, e);
                    }
                }
            }
        }

        private void txtCreateProdQuantity_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void txtCreateProdPrice_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) &&
       (e.KeyChar != '.'))
            {
                e.Handled = true;
            }

            if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
            {
                e.Handled = true;
            }
        }

        private void txtCreateProdNetPrice_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) &&
(e.KeyChar != '.'))
            {
                e.Handled = true;
            }

            if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
            {
                e.Handled = true;
            }

        }

        private void button4_Click_1(object sender, EventArgs e)
        {
            DailySalesForm dsf = new DailySalesForm();
            dsf.ShowDialog();
            button5_Click(sender, e);
        }

        private void button5_Click(object sender, EventArgs e)
        {
            DailySales ds = new DailySales();
            ds.LoadAll();
            grdViewDailySales.AutoGenerateColumns = false;
            grdViewDailySales.DataSource = ds.DefaultView;

            DailySales ds2 = new DailySales();
            ds2.getDistinctDS();

            DataTable dsdt = new DataTable();
            dsdt = ds2.DefaultView.ToTable();
            List<string> dailySalesDays = new List<string>();
            dailySalesDays.AddRange(dsdt.Rows.OfType<DataRow>().Select(dr => dr.Field<string>("DailySaleDate")).ToList());
            dailySalesDays.Insert(0, "الكل");

            cbDailySalesDays.DataSource = dailySalesDays;

            cbDailySalesDays.SelectedIndex = 0;
            DailySales ds3 = new DailySales();
            ds3.LoadAll();
            grdViewDailySales.DataSource = ds3.DefaultView;
        }

        private void button3_Click_1(object sender, EventArgs e)
        {
            if (cbDailySalesDays.Text == "الكل")
            {
                button5_Click(sender, e);
            }
            else
            {
                DailySales ds = new DailySales();
                ds.Where.DailySaleDate.Value = cbDailySalesDays.Text;
                ds.Where.DailySaleDate.Operator = MyGeneration.dOOdads.WhereParameter.Operand.Equal;
                ds.Query.Load();

                grdViewDailySales.DataSource = ds.DefaultView;
            }
        }

        private void grdViewDailySales_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            var senderGrid = (DataGridView)sender;

            if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn && e.RowIndex >= 0)
            {
                if (senderGrid.Columns[e.ColumnIndex].HeaderText == "مسح")
                {
                    DialogResult res = MessageBox.Show("هل تريد مسح هذا السجل نهايئا ؟", "تأكيد المسح", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (res == DialogResult.Yes)
                    {
                        string dsID = grdViewDailySales["DailySaleID", e.RowIndex].Value.ToString();
                        DailySales ds = new DailySales();
                        ds.LoadByPrimaryKey(int.Parse(dsID));
                        ds.MarkAsDeleted();
                        ds.Save();

                        button3_Click_1(sender, e);
                    }
                }
            }
        }
        private void btnSearch_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtSearchProdNum.Text))
            {
                Products pro = new Products();
                if (comboColor.Text == "الكل" && comboSize.Text == "الكل" && comboTybe.Text == "الكل" && comboCat.Text == "الكل" && radioBtnAll.Checked)
                {
                    pro.LoadAll();
                }
                else
                {
                    if (comboColor.Text != "الكل")
                    {
                        pro.Where.ProdColor.Value = comboColor.Text;
                        pro.Where.ProdColor.Operator = MyGeneration.dOOdads.WhereParameter.Operand.Equal;
                        pro.Where.ProdColor.Conjuction = MyGeneration.dOOdads.WhereParameter.Conj.And;
                    }
                    if (comboCat.Text != "الكل")
                    {
                        int catID = 0;
                        switch (comboCat.Text)
                        {
                            case "حذاء":
                                catID = 1;
                                break;
                            case "شنطة":
                                catID = 2;
                                break;
                            default:
                                break;
                        }
                        pro.Where.CatID.Value = catID;
                        pro.Where.CatID.Operator = MyGeneration.dOOdads.WhereParameter.Operand.Equal;
                        pro.Where.CatID.Conjuction = MyGeneration.dOOdads.WhereParameter.Conj.And;
                    }
                    if (comboSize.Text != "الكل")
                    {
                        pro.Where.ProdSize.Value = comboSize.Text;
                        pro.Where.ProdSize.Operator = MyGeneration.dOOdads.WhereParameter.Operand.Equal;
                        pro.Where.ProdSize.Conjuction = MyGeneration.dOOdads.WhereParameter.Conj.And;
                    }
                    if (comboTybe.Text != "الكل")
                    {
                        pro.Where.ProdType.Value = comboTybe.Text;
                        pro.Where.ProdType.Operator = MyGeneration.dOOdads.WhereParameter.Operand.Equal;
                        pro.Where.ProdType.Conjuction = MyGeneration.dOOdads.WhereParameter.Conj.And;
                    }
                    if (!radioBtnAll.Checked)
                    {
                        if (radioBtnNotSoiree.Checked)
                        {
                            pro.Where.ProdIsSoiree.Value = 0;
                            pro.Where.ProdIsSoiree.Operator = MyGeneration.dOOdads.WhereParameter.Operand.Equal;
                            pro.Where.ProdIsSoiree.Conjuction = MyGeneration.dOOdads.WhereParameter.Conj.And;
                        }
                        else if (radioBtnSoiree.Checked)
                        {
                            pro.Where.ProdIsSoiree.Value = 1;
                            pro.Where.ProdIsSoiree.Operator = MyGeneration.dOOdads.WhereParameter.Operand.Equal;
                            pro.Where.ProdIsSoiree.Conjuction = MyGeneration.dOOdads.WhereParameter.Conj.And;
                        }
                    }
                }
                pro.Query.Load();
                GrdSearch.AutoGenerateColumns = false;
                GrdSearch.DataSource = pro.DefaultView;
            }
            else
            {
                Products pro = new Products();
                pro.LoadByPrimaryKey(int.Parse(txtSearchProdNum.Text));
                if (pro.RowCount > 0)
                {
                    GrdSearch.DataSource = pro.DefaultView;
                }
                else
                {
                    GrdSearch.DataSource = "";
                }
            }


        }
        private void txtProdNum_TextChanged_1(object sender, EventArgs e)
        {
            if (txtProdNum.Text.Length >= 5)
            {
                Products Prodd = new Products();
                Prodd.LoadByPrimaryKey(int.Parse(txtProdNum.Text));
                if (Prodd.RowCount > 0)
                {
                    ComboProdName.SelectedValue = txtProdNum.Text;
                    //ComboProdName.Text = Prodd.ProdName;
                    //txtPrice.Text = Prodd.ProdPrice.ToString();
                    //txtAvalbilePieces.Text = Prodd.ProdQuantity.ToString();
                    //ComboProdName.SelectedValue = Prodd.ProdID;
                }
                if (txtNumOfProd.Text == "1")
                {
                    textBox1.Text = txtPrice.Text;
                }
            }
        }
        private void grdCasher_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            var sendergrid = (DataGridView)sender;
            if (sendergrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn && e.RowIndex >= 0)
            {
                float num = float.Parse(Program.grdCasherDT.Rows[e.RowIndex]["اجمالى السعر"].ToString());
                lblTotalInvoice.Text = (float.Parse(lblTotalInvoice.Text) - num).ToString();

                Program.grdCasherDT.Rows.RemoveAt(e.RowIndex);
                //float num = float.Parse(Program.grdCasherDT.Columns["اجمالى السعر"].Table.Rows[e.RowIndex].ToString());
            }
        }

        private void btnAdd_Click_1(object sender, EventArgs e)
        {
            try
            {
                string tempr = txtProdNum.Text;
                string temprCount = txtNumOfProd.Text;
                ComboProdName.SelectedIndex = 0;
                ComboProdName.SelectedValue = tempr;
                txtNumOfProd.Text = temprCount;
                Program.grdCasherDT.Rows.Add(int.Parse(txtProdNum.Text), (ComboProdName.Text).ToString(), int.Parse(txtNumOfProd.Text), float.Parse(textBox1.Text));

                grdCasher.DataSource = Program.grdCasherDT.DefaultView;

                lblTotalInvoice.Text = (float.Parse(lblTotalInvoice.Text) + float.Parse(textBox1.Text)).ToString();
            }
            catch (Exception)
            {
                MessageBox.Show("لقد فشلت العملية", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void ComboProdName_SelectedValueChanged(object sender, EventArgs e)
        {

        }

        private void txtNumOfProd_TextChanged(object sender, EventArgs e)
        {
            if (txtNumOfProd.Text != null)
            {
                textBox1.Text = ((float.Parse(txtNumOfProd.Text) * float.Parse(txtPrice.Text)).ToString());
                checkQuan();
            }
        }

        private void txtProdNum_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void ComboProdName_Leave(object sender, EventArgs e)
        {

        }

        private void txtProdNum_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                txtNumOfProd.Focus();
            }
        }

        private void txtNumOfProd_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (btnAdd.Enabled == true)
                {
                    btnAdd_Click_1(sender, e);
                }
                txtProdNum.Focus();
                txtProdNum.SelectionStart = 0;
                txtProdNum.SelectionLength = txtProdNum.Text.Length;
            }
            if (e.KeyCode == Keys.Oemplus || e.KeyCode == Keys.Add)
            {
                btnNumPlus_Click(sender, e);
            }
            if (e.KeyCode == Keys.OemMinus || e.KeyCode == Keys.Subtract)
            {
                btnNumMinus_Click(sender, e);
            }
        }

        private void txtSearchProdNum_TextChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(txtSearchProdNum.Text))
            {
                comboCat.Enabled = false;
                comboColor.Enabled = false;
                comboTybe.Enabled = false;
                comboSize.Enabled = false;
                groupBoxSoiree.Enabled = false;
            }
            else
            {
                comboCat.Enabled = true;
                comboColor.Enabled = true;
                comboTybe.Enabled = true;
                comboSize.Enabled = true;
                groupBoxSoiree.Enabled = true;
            }
        }

        private void tabControl1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnSearch_Click(sender, e);
            }
        }

        private void txtSearchProdNum_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void button7_Click(object sender, EventArgs e)
        {
            Products prod4 = new Products();
            prod4.LoadAll();
            DataTable dt = prod4.DefaultView.ToTable();
            List<int> prodListID = new List<int>();
            prodListID.AddRange(dt.Rows.OfType<DataRow>().Select(dr => dr.Field<int>("ProdID")).ToList());
            var str3 = new AutoCompleteStringCollection();

            string[] arrayStr = Array.ConvertAll(prodListID.ToArray(), element => element.ToString());

            str3.AddRange(arrayStr);

            Products pro = new Products();
            pro.LoadAll();
            GrdSearch.AutoGenerateColumns = false;
            GrdSearch.DataSource = pro.DefaultView;

            ColorSearch();
            TypeSearch();
            CatSearch();
            SizeSearch();

            txtSearchProdNum.AutoCompleteCustomSource = str3;




            txtSearchProdNum.Text = "";
            comboCat.SelectedIndex = 0;
            comboColor.SelectedIndex = 0;
            comboTybe.SelectedIndex = 0;
            comboSize.SelectedIndex = 0;
            radioBtnAll.Checked = true;
            btnSearch_Click(sender, e);
        }

        private void button6_Click(object sender, EventArgs e)
        {
            Sales sls = new Sales();
            if (comboBoxSalesDays.Text != "الكل")
            {
                sls.getSaledProducts(comboBoxSalesDays.Text);
            }
            else
            {
                sls.getSaledProducts("getAll");
            }
            gridViewSales.DataSource = sls.DefaultView;
        }

        private void button8_Click(object sender, EventArgs e)
        {
            Sales sls = new Sales();
            sls.getSaledProducts("getAll");
            gridViewSales.AutoGenerateColumns = false;
            gridViewSales.DataSource = sls.DefaultView;

            Sales sls2 = new Sales();
            sls2.getDistinctSalesDates();
            DataTable dt3 = sls2.DefaultView.ToTable();
            List<string> salesDays = new List<string>();
            salesDays.AddRange(dt3.Rows.OfType<DataRow>().Select(dr => dr.Field<string>("SaleDate")).ToList());
            salesDays.Insert(0, "الكل");
            comboBoxSalesDays.DataSource = salesDays;

            txtProdNum.Focus();
            txtProdNum.SelectAll();

            comboBoxSalesDays.SelectedIndex = 0;
            button6_Click(sender, e);
        }

        private void gridViewSales_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            var senderGrid = (DataGridView)sender;

            if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn && e.RowIndex >= 0)
            {
                if (senderGrid.Columns[e.ColumnIndex].HeaderText == "مسح")
                {
                    DialogResult res = MessageBox.Show("هل تريد مسح هذا السجل نهايئا ؟", "تأكيد المسح", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (res == DialogResult.Yes)
                    {
                        string sID = gridViewSales["SaleID", e.RowIndex].Value.ToString();
                        Sales sls = new Sales();
                        sls.LoadByPrimaryKey(int.Parse(sID));
                        sls.MarkAsDeleted();
                        sls.Save();
                        button6_Click(sender, e);
                    }
                }
            }
        }

        private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)
        {
            try
            {
                Sales sls = new Sales();
                sls.getProfitSaledPieces(monthCalendar1.SelectionRange.Start.ToShortDateString());
                DataTable dt = sls.DefaultView.ToTable();
                lblProfitSaledPieces.Text = dt.Rows[0]["SaleQuantity"].ToString();
                //--
                sls.getProfitTotalNetPrice(monthCalendar1.SelectionRange.Start.ToShortDateString());
                dt = sls.DefaultView.ToTable();
                lblProfitTotalNetPrice.Text = dt.Rows[0]["TotalNetPrice"].ToString();
                //--
                sls.getProfitTotalPrice(monthCalendar1.SelectionRange.Start.ToShortDateString());
                dt = sls.DefaultView.ToTable();
                lblProfitTotalPrice.Text = dt.Rows[0]["SaledPrice"].ToString();
                //--
                sls.getProfitTotalDailySales(monthCalendar1.SelectionRange.Start.ToShortDateString());
                if (sls.RowCount > 0)
                {
                    dt = sls.DefaultView.ToTable();
                    //if (string.IsNullOrWhiteSpace(dt.Rows[0]["DailySalePaid"].ToString()))
                    //{
                    lblProfitTotalDailySales.Text = dt.Rows[0]["DailySalePaid"].ToString();
                    //}
                }
                //--
                try
                {
                    lblProfit.Text = (float.Parse(lblProfitTotalPrice.Text) - (float.Parse(lblProfitTotalNetPrice.Text) + float.Parse(lblProfitTotalDailySales.Text))).ToString();
                }
                catch (Exception)
                {
                    lblProfit.Text = (float.Parse(lblProfitTotalPrice.Text) - (float.Parse(lblProfitTotalNetPrice.Text))).ToString();
                }
            }
            catch (Exception)
            {
                lblProfitSaledPieces.Text = "-";
                lblProfitTotalNetPrice.Text = "-";
                lblProfitTotalPrice.Text = "-";
                lblProfitTotalDailySales.Text = "-";
                lblProfit.Text = "-";
            }
        }

        private void GrdSuppliers_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            var senderGrid = (DataGridView)sender;

            if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn && e.RowIndex >= 0)
            {
                if (senderGrid.Columns[e.ColumnIndex].HeaderText == "تعديل")
                {
                    Program.SupID = int.Parse(GrdSuppliers["ColSupplierID", e.RowIndex].Value.ToString());
                    txtSupplierName.Text = GrdSuppliers["ColSupplierName", e.RowIndex].Value.ToString();
                    txtSupplierPhone.Text = GrdSuppliers["ColSupplierPhone", e.RowIndex].Value.ToString();
                    txtTotalBalance.Text = GrdSuppliers["ColTotalBalance", e.RowIndex].Value.ToString();
                    txtPaidBalanace.Text = GrdSuppliers["ColPaidBalance", e.RowIndex].Value.ToString();
                    txtRemainBalance.Text = GrdSuppliers["ColRemainBalance", e.RowIndex].Value.ToString();

                    btnCreateSupplier.Text = "تعديل";
                    btnCreateSupplier.BackColor = Color.Orange;
                }
                else if (senderGrid.Columns[e.ColumnIndex].HeaderText == "مسح")
                {
                    DialogResult res = MessageBox.Show("هل تريد مسح هذا المنتج نهايئا ؟", "تأكيد المسح", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (res == DialogResult.Yes)
                    {
                        // string SupID = GrdSuppliers["ColSupplierID", e.RowIndex].Value.ToString();
                        string SupID = GrdSuppliers["ColSupplierID", e.RowIndex].Value.ToString();
                        Suppliers deleteSupplier = new Suppliers();
                        deleteSupplier.LoadByPrimaryKey(int.Parse(SupID));
                        deleteSupplier.MarkAsDeleted();
                        deleteSupplier.Save();

                        btnRefreshSupplier_Click(sender, e);
                    }
                }
            }
        }

        private void textBox3_TextChanged(object sender, EventArgs e)
        {

        }

        private void label28_Click(object sender, EventArgs e)
        {

        }

        private void button10_Click(object sender, EventArgs e)
        {
            txtSupplierName.Text = "";
            txtSupplierPhone.Text = "";
            txtTotalBalance.Text = "";
            txtPaidBalanace.Text = "";
            txtRemainBalance.Text = "";
            btnCreateSupplier.Text = "انشاء";
            btnCreateSupplier.BackColor = Color.LightGreen;
            Program.SupID = 0;
        }

        private void btnRefreshSupplier_Click(object sender, EventArgs e)
        {
            Suppliers sup = new Suppliers();
            sup.LoadAll();
            GrdSuppliers.AutoGenerateColumns = true;
            GrdSuppliers.DataSource = sup.DefaultView;
        }

        private void btnCreateSupplier_Click(object sender, EventArgs e)
        {
            Suppliers NewSupplier = new Suppliers();
            if (Program.SupID == 0)
            {
                NewSupplier.AddNew();
            }
            else
            {
                NewSupplier.LoadByPrimaryKey(Program.SupID);
            }
            NewSupplier.SupplierName = txtSupplierName.Text;
            NewSupplier.SupplierPhone = txtSupplierPhone.Text;
            NewSupplier.SupplierTotalBalance = float.Parse(txtTotalBalance.Text);
            NewSupplier.SupplierPaidBalance = float.Parse(txtPaidBalanace.Text);
            NewSupplier.SupplierRemainBalance = float.Parse(txtRemainBalance.Text);
            NewSupplier.Save();

            btnRefreshSupplier_Click(sender, e);
            MessageBox.Show("تمت العملية بنجاح", "Done", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void txtTotalBalance_TextChanged(object sender, EventArgs e)
        {
            txtPaidBalanace_TextChanged(sender, e);
        }

        private void txtPaidBalanace_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (txtPaidBalanace.Text != null)
                {
                    txtRemainBalance.Text = (float.Parse(txtTotalBalance.Text) - float.Parse(txtPaidBalanace.Text)).ToString();
                }
                else if (txtPaidBalanace.Text == null)
                {
                    MessageBox.Show("تأكد من الخانات الفارغة", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch
            {

            }
        }

        private void txtTotalBalance_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) &&
(e.KeyChar != '.'))
            {
                e.Handled = true;
            }

            if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
            {
                e.Handled = true;
            }
        }

        private void txtPaidBalanace_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) &&
(e.KeyChar != '.'))
            {
                e.Handled = true;
            }

            if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
            {
                e.Handled = true;
            }
        }

        private void button9_Click(object sender, EventArgs e)
        {
            Products prod = new Products();
            prod.GetComboProdName();
            ComboProdName.DataSource = prod.DefaultView;
            ComboProdName.DisplayMember = "Name";
            ComboProdName.ValueMember = "ProductID";
            ComboProdName.SelectedValueChanged += ComboProdName_SelectedValueChanged2;
            try
            {
                ComboProdName.SelectedIndex = 1;
                ComboProdName.SelectedIndex = 0;
            }
            catch (Exception)
            {
                
            }

            Products prod4 = new Products();
            prod4.LoadAll();
            DataTable dt = prod4.DefaultView.ToTable();
            List<int> prodListID = new List<int>();
            prodListID.AddRange(dt.Rows.OfType<DataRow>().Select(dr => dr.Field<int>("ProdID")).ToList());
            var str3 = new AutoCompleteStringCollection();

            string[] arrayStr = Array.ConvertAll(prodListID.ToArray(), element => element.ToString());

            str3.AddRange(arrayStr);
            txtProdNum.AutoCompleteCustomSource = str3;
        }

        private void button10_Click_1(object sender, EventArgs e)
        {
            if (Camelio.Properties.Settings.Default.LoginType == "admin")
            {
                Camelio.Properties.Settings.Default.LoginType = "";
                Camelio.Properties.Settings.Default.Save();
                Application.Restart();
            }
            else
            {
                AuthenticationForm af = new AuthenticationForm();
                af.Show();
                this.Hide();
                af.FormClosing += af_FormClosing;
            }
        }

        void af_FormClosing(object sender, FormClosingEventArgs e)
        {
            //this.Close();
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            Application.Exit();
        }
    }
}
        
    
